var config={
    publicUrl:"http://localhost:3000/users/"
};



//初始化表格
$('#user').datagrid({
    url:`${config.publicUrl}list`,
    pagination:true,
    method:"post",
    fit:true,
    striped:true,
    nowrap:true,
    fitColumns:true,
    columns:[[
		{field:'ck',checkbox:true},
		{field:'username',title:'用户名',width:60},
        {field:'password',title:'密码',width:100,
        formatter:function(value,row,index){
            return '●'.repeat(row.password.length);
        }
    },
		{field:'email',title:'邮箱',width:150,align:'left'},
		{field:'age',title:'年龄',width:60,align:'center'},
		{field:'sex',title:'性别',width:60,align:'center',
        formatter: function(value,row,index){
        //   console.log(row)
            if(row.sex){
                return '男';
            }else{
                return '女';
            }
        }},
		{field:'address',title:'家庭地址',align:'left'},
        {field:'problem',title:'找回问题',width:150,align:'left',
        formatter: function(value,row,index){
            //    console.log(row.problem)
                if(row.problem){
                    return row.problem.title+'--->'+row.problem.question;
                }else{
                    return '该用户没有设置找回问题';
                }
            }
        },
        {field:'drink',title:'饮料',width:60,align:'center',
        formatter: function(value,row,index){
        //   console.log(row)
            if(row.drink=="Tea"){
                return '茶';
            }else{
                return '咖啡';
            }
        }
    },
        {field:'hobbies',title:'爱好',width:60,align:'center',
        formatter: function(value,row,index){
            var hobbies_txt="";
            var num=row.hobbies.length;
            for(var i=0;i<num;i++){
                hobbies_txt+=row.hobbies[i]+",";
            }
                return hobbies_txt;
        }
    },
        {field:'reg_data',title:'注册时间',width:150,align:'center',
        formatter: function(value,row,index){
            // console.log(row.reg_data);
            return moment(row.reg_data).utcOffset(480).format('YYYY-MM-DD HH:mm:ss');
            }
        },
        {field:'manager',title:'操作',width:100,align:'center',
        formatter: function(value,row,index){
            return `<a class="easyui-linkbutton" href="javascript:void(0);UpdataRow('${row._id}')">修改</a> <a class="easyui-linkbutton" href="javascript:void(0);DeleteRow('${row._id}')">删除</a>`;
            }
        }
    ]],
    toolbar: [{
        text:"添加用户数据",
		iconCls: 'icon-add',
		handler: function(){
            $('input[name=tab]').val("");
            $('#form').form('reset');
            $('#dialog').dialog("open");
        }
	},{
        text:"移除多个用户信息",
		iconCls: 'icon-help',
		handler: function(){
            //getSelections
            $.messager.confirm('Confirm','您确定要删除选中数据吗?',function(r){
                if (r){
                    var select=$("#user").datagrid("getSelections");
                    var ids=[];
                    if(select.length>0){
                            for(let i=0;i<select.length;i++){
                                ids.push(select[i]._id);
                            }
                            $.ajax({
                                url:`${config.publicUrl}removes`,
                                method:"delete",
                                data:{ids:ids.toString()}//转出字符串
                            }).then(res=>{
                                // console.log(res)
                                $('#user').datagrid('reload');
                            });
                    }else{
                        alert("对不起您还没有选中");
                    }
                }
            });
        }
    },
    {
        text:'查询数据',
		iconCls: 'icon-search',
		handler: function(){
            $("#user").datagrid({
                url:`${config.publicUrl}list`,
                method:"post",
                queryParams:{
                    search:$("input[name=search]").val(),
                    sex:$("input[name=sexs]:checked").val()
                }
            });
        }
	}],
    //数据加载成功以后渲染
    onLoadSuccess: function(data) {
        if(data.total==0){
           $(".datagrid-body:eq(1)").html('<p style="text-align:center;font-size:20px">对不起,获取不到数据</p>');
        }
        $("#searchtext").remove();
        var saerch='<div id="searchtext"><input type="radio" name="sexs" value="false" checked>male<input type="radio" name="sexs" value="true">man <input class="easyui-textbox" name="search" style="width:100px"></div> '
        $(".datagrid-toolbar>table td:eq(2)").before(saerch);
        $.parser.parse();
    }
});



//添加自定义验证规则

$.extend($.fn.validatebox.defaults.rules, {
    password: {
		validator: function(value, param){
            return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,64}$/i.test(value);
		},
		message: '密码只能为6~64位的字母混合数字'
    },
    age: {
		validator: function(value, param){
            return value<18?false:true
		},
		message: '对不起您未满十八周岁'
    }
});



//tip配置消息提示弹出框===》备用
$('#tip').dialog({
    title: '消息提示',
    width: 400,
    height: 200,
    closed: true,
    cache: false,
    // href: 'get_content.php',
    modal: true
});


//dialog配置新增/修改窗口
$('#dialog').dialog({
    title: '数据修改/增加',
    width: 800,
    height:600,
    closed: true,
    cache: false,
    modal: true
});




//提交表单数据(添加数据)
function submitForm(){
    $('#form').form('submit',{
        onSubmit:function(){
            if($(this).form('enableValidation').form('validate')){
                if($('input[name=tab]').val()==""){
                    const data=$('#form').serializeJSON();
                    //  console.log(data);
                    data.problem=JSON.stringify(data.problem);
                    $.ajax({
                        url:`${config.publicUrl}create`,
                        method:"post",
                        data:data,
                        traditional:true, //默认false
                    }).then(res=>{
                        // console.log(res);
                        $('#dialog').dialog("close");
                        $('#user').datagrid('reload');
                    })
                }else{
                    const data=$('#form').serializeJSON();
                    //  console.log(data);
                    data.problem=JSON.stringify(data.problem);
                    $.ajax({
                        url:`${config.publicUrl}update/${$('input[name=tab]').val()}`,
                        method:"put",
                        data:data,
                        traditional:true, //默认false
                    }).then(res=>{
                        // console.log(res);
                        $('#dialog').dialog("close");
                        $('#user').datagrid('reload');
                    })
                }
            }
            return false;
        }
    });
}

//重置表单

function clearForm(){
    $('#form').form('reset');
}


//修改单行数据
function UpdataRow(id){
    $('input[name=tab]').val(id);
    $.ajax({
        url:`${config.publicUrl}list/${id}`,
        method:"get",
    }).then(res=>{
        var special={
            "problem[title]":res.problem.title,
            "problem[question]":res.problem.question,
            "hobbies[]":res.hobbies,
        }
         $('#form').form('load',res);
         $('#form').form('load',special);
    });
    $('#dialog').dialog("open");
}


//删除单行数据

function DeleteRow(id){
    $.messager.confirm('Confirm','您确定要删除该用户数据吗?',function(r){
        if (r){
            $.ajax({
                url:`${config.publicUrl}delete/${id}`,
                method:"delete",
            }).then(res=>{
                $('#user').datagrid('reload');
                //  console.log(res);
            });
        }
    });
}



